import {findLeftMenuAntTabs} from '@/api/menu'
const maintabs = {
    state:{
        tabs:[
            {route:'/index/first',name:'首页',closable:false}
        ],
        openKeys:[''],
        activeRoute:'/index/first',
        tabList:[],
        menuList:[],
        addTabName:''
    },
    mutations: {
        addTabMutation(state,route){
            let isAlreadyIn = state.tabs.some(item => item.route === route)
            this.commit('findMenuNameByRoute',route);
            state.activeRoute = route
            console.log("vuex里的activeRoute:"+state.activeRoute)
            if (!isAlreadyIn&&state.addTabName!==''&&state.addTabName!=='/'&&state.addTabName!=='/login'){
                console.log('添加Tab'+route)
                state.tabs.push({route:route,name: state.addTabName,closable:true})
            }
        },
        removeTab(state,route){
            if (route!=='/index/first'){
                state.tabs = state.tabs.filter(item => item.route!== route)
                state.activeRoute = state.tabs[state.tabs.length-1].route
            }
        },
        findMenuNameByRoute(state,route){
            let findOne;
            for (let i of state.tabList){
                if (i.children&&i.children.length>=1){
                    let tempArr = i.children.filter(item => item.path===route)
                    if (tempArr.length>0){
                        findOne = tempArr[0]
                        if (i.path){
                            state.openKeys = [i.path]
                        }
                        break;
                    }
                }else {
                    if (i.path===route){
                        findOne=i;
                        state.openKeys = ['']
                        break;
                    }
                }

            }
            console.log("vuex里的openKeys",state.openKeys);
            state.addTabName = findOne?findOne.menuName:''
        },
        setOpenKeys(state,openKeys){
            state.openKeys = openKeys
        },
        setMenuListAndTabs(state,data){
            state.tabList = data.tabs
            state.menuList = data.menuList
        }
    },
    actions: {
        addTab({state,commit},route){
            //因为menuList里面有一项非菜单路由
            //大于等于一表示菜单已经加载过了，并且页面没刷新，
            //只是切换路由组件,不重新加载菜单
            if(state.menuList.length <1){
                findLeftMenuAntTabs()
                    .then(res=>{
                        commit('setMenuListAndTabs',res.data)
                        commit("addTabMutation",route);//菜单加载完成之后将Tab导航项添加
                    })
            }else{
                commit("addTabMutation",route);//菜单加载完成之后将Tab导航项添加
            }
        }
    },
    getters:{

    }
}

export default maintabs
